package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.salesmanage.util.Profession;
import com.turing.post.salesmanage.util.ProfessionDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

@Stateless(mappedName = "salesmanage.impl.ProfessionDaoImpl")
@Remote
@Local
public class ProfessionDaoImpl implements ProfessionDao {

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao pcpsCommonDaoImpl;
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@Override
	public Profession getProfessionByProfessionId(BigInteger professionId) {
		return _em.find(Profession.class, professionId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Profession getProfessionByProfessionNo(String professionNo) {
		String sql = "select * from Profession t where professionNo=?1";
		Query query = _em.createNativeQuery(sql, Profession.class);
		query.setParameter(1, professionNo);
		List<Profession> list = query.getResultList();
		if (list == null || list.size() < 1) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public void insertProfession(Profession profession)
			throws PCPSApplicationException {
		profession.setProfessionId(pcpsCommonDaoImpl.getUniqueIntegerKey());
		GeneralDao.insert(_em, profession);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Profession> getFirstProfessionList() {
		String sql = "select * from Profession t where length(t.professionno)=1 order by t.professionid";
		Query query = _em.createNativeQuery(sql, Profession.class);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Profession> getProfessionList(String superprofessionno) {
		String sql = "";
		if (PCPSUtil.isEmpty(superprofessionno)) {
			sql = "select t.* from Profession t order by t.professionNo";
		} else {
			sql = "select t.* from Profession t where superprofessionno='"
					+ superprofessionno + "' order by t.professionNo";
		}
		Query query = _em.createNativeQuery(sql, Profession.class);
		return query.getResultList();
	}
}
